<?php
	//include_once("cmsMailoutConfig.php");

	include_once(CMS_HOME_DIR . "/files/cmsFiles.php");

	
	define("CMS_CONTENTBUILDER_IMAGE_BLOCK_CLASS","CmsImageContentBlock");
	
	/** super class for all cms mailout contentblocks */
	class  CmsBodyContentBlock extends CmsContentBlock {
		var $imageBlocks = array("68" => "leftImage","70" => "centreImage","69" => "rightImage");
		
		var $TINYMCE_CSS = TINYMCE_CSS;
		var $TINYMCE_TAGS = TINYMCE_TAGS; 
		var $TINYMCE_STYLES =  TINYMCE_STYLES;

		var $imageBlockClass = CMS_CONTENTBUILDER_IMAGE_BLOCK_CLASS;
		
		function CmsBodyContentBlock () {
			parent::CmsContentBlock();
			//myPrintR($parent);
			 $this->keys = array_merge_recursive(
			 array(
			 		EXTRACT_STRING => array(
			 			"bodyContent",
			 			"title"
			 		)
			 	),
			 	array(
			 		EXTRACT_NUMBER => array (
				 		"pageOrder"
			 		)
			 	),
				 array(
				 	EXTRACT_TO_ONE_OBJECT => array(
				 		"leftImage",
				 		"rightImage",
				 		"centreImage"
				 	)
				 )
			 	,$this->keys);

			 $this->dataModelKeyMapping = array_merge(
			 	$this->dataModelKeyMapping,
			 	array(
			 		"title" => "title",
			 		"bodyContent" => "content",
			 		"pageOrder" => "extra2",
			 		//one to one objects//
			 		"leftImage" => "extra3",
			 		"centreImage" => "extra4",
			 		"rightImage" => "extra5",

			 		// do i map the objects this way not sure
			 	)
			 );

			$this->actions = array_merge($this->actions, "increasePageOrder","decreasePageOrder","addImage","deleteImage","updateImage");
			$this->documentTypeCode ='bodyBlock';
			$this->contentBlockImages = array();
			$this->formId = 173;
		}

		function cmsDocument() {
			$db = &$_SESSION['db'];
			return new CmsDocument($db);
		}

		function &imageContentBlockForId($id) {
			foreach($this->valueForKey('imageBlocks') as $imageBlockType=>$imageBlock ) {
				$imBlock = $this->valueForKey($imageBlock);
				if (!is_null($imBlock) && $imBlock->id() == $id) {
					return $imBlock;
				}
			}
			$null = null;
			return ($null);//fucking broken pointers ...
		}

		function decreasePageOrderAction(){
			$po = $this->valueForKey('pageOrder');
			if ( is_null($po)) {
				$po = 0;
			} else  {
				$po = $po-1.5;
			}
			$this->takeValueForKey($po,'pageOrder');
		}

		function increasePageOrderAction() {
			$po = $this->valueForKey('pageOrder');
			if ( is_null($po)) {
				$po = 0;
			} else {//need a limit here.. but what..
				$po = $po + 1.5;//we want to go in steps of more than one.. so we will always move over something - assuming that every thing is in order.
			}
			$this->takeValueForKey($po,'pageOrder');
		}

		function generateForm(&$db) {
			
			if (isset($GLOBALS['cmsKvcO']) && is_object($GLOBALS['cmsKvcO']) && is_a($GLOBALS['cmsKvcO'],'cmsmailout')) {
				$mailoutObj = $GLOBALS['cmsKvcO'];
			}
			
			//echo $this->TINYMCE_CSS;	
			
			if (isset($mailoutObj) && is_object($mailoutObj)) {
				$template = $mailoutObj->valueForKey("template");
				
				if ($template) {
					$this->TINYMCE_CSS = "/html/css.php?template=".$template;
				}
			}
			//echo $this->TINYMCE_CSS;
			$contentBlockContentId = $this->keyForField("bodyContent");
			$content = $this->valueForKey('bodyContent');

			$contentBlockTitleId = $this->keyForField("title");
			$title = str_replace('"',"&quot;",$this->valueForKey('title'));

			$increasePageOrderActionId = $this->keyForField('increasePageOrder') . "_1";
			$decreasePageOrderActionId = $this->keyForField('decreasePageOrder') . "_1";

			$id = $this->id();
			$pageOrder = $this->valueForKey('pageOrder');
			$invalidKeys = 	$this->valueForKey('invalidKeys');
			$form = <<< EOD
<div id="$id" class="cmsMailoutBodyContentBlock" align="left">
	<table border="0" cellspacing="0" cellpadding="0">
	  <!-- Title  -->
          <tr  >
          
	    <td  class="cms_form_label">Heading:</td>
            <td class="cms_form_element">
            	

      		<input type="text" id="$contentBlockTitleId" name="$contentBlockTitleId" value="$title" class="cmsMailout"/>

			<input onClick="return imageSubmit(this);" src="Mailout/images/mailout_moveUp.gif" class="cmsMailoutButton" type="image" id="$decreasePageOrderActionId" name="$decreasePageOrderActionId" value="Move Up" />

			<input onClick="return imageSubmit(this);" src="Mailout/images/mailout_moveDown.gif" class="cmsMailoutButton" type="image" id="$increasePageOrderActionId" name="$increasePageOrderActionId" value="Move Down" />

				
EOD;
if (!$this->isKeyValid('title')) {
	$form .= "<br /><span class=\"validationError\"> Title ".$invalidKeys['title'].".</span>\n";
}
			$form .= <<< EOD
       </td>
	  </tr>
          <tr>
            <td height="1" width="160"><img src="/cms/images/spacer.gif" height="5" width="160" /></td>
            <td height="1"><img src="/cms/images/spacer.gif" height="5" width="1" /></td>
          </tr>
	  <!-- Text Content TextArea -->
      <tr>
	    <td colspan="2" class="cms_form_label">Text Content:</td>
	  </tr>
	  <tr>
            <td colspan="2" align="left">
<div class="pageBuilderContentblock">            
EOD;
	$form .= tinyMceEditorWithIdAndContent( $contentBlockContentId, $content, ($hack = array("inputClass" => "cmsMailout", "tinyMceTags" => $this->TINYMCE_TAGS, "tinyMceCss" => $this->TINYMCE_CSS,"tinyMceStyles" => $this->TINYMCE_STYLES  )));

	
	if (!$this->isKeyValid('bodyContent')) {
		$form .= "<br /><span class=\"validationError\"> Text Content ".$invalidKeys['bodyContent'].".</span>\n";
	}
			$form .= <<< EOD
			</div>
	    </td>
          </tr>
          <tr>
            <td height="1" width="160"><img src="/cms/images/spacer.gif" height="5" width="160" /></td>
            <td height="1"><img src="/cms/images/spacer.gif" height="5" width="1" /></td>
          </tr>
	</table>
		
	<table border="0" cellspacing="0" cellpadding="0">
<tr>
EOD;

			//the image types that are suitable for the body block  in order of appearance
			//
			$nid = 1;
			$posText = array(1=>'Left Image', 2=>'Centre Image', 3=>'Right Image');
			foreach($this->valueForKey('imageBlocks') as $imageBlockType=>$imageBlock) {
				$imBlock = $this->valueForKey($imageBlock);
				$f=null;
				if (!is_null($imBlock)){
					$f = $imBlock->generateForm($db);//what is this here..
				}

				$form .=  <<< EOD
		<td width="30%" valign="top">
		<div style="font-weight:bold;padding:5px 0 0 0">$posText[$nid]</div><br />
$f
EOD;
				$fileTypeCode=null;
				if (!is_null($imBlock)){
					//if we dont have an image.. allow us to
					//$form .= "add";
					$deleteImageAction = $this->keyForField('deleteImage') . "_$nid";
					$deleteImageActionArgument = $deleteImageAction . "_1";
					$form .= <<< EOD

					<input onClick="return imageSubmit(this);" src="Mailout/images/mailout_delete.gif" class="cmsMailoutBodyContentBlockDeleteButtons" type="image" id="$deleteImageAction" name="$deleteImageAction" value="Delete Image" />
					
<input type="hidden" id="$deleteImageActionArgument" name="$deleteImageActionArgument" value="$imageBlock"/>
EOD;
	//need to add blocks here.. for the image caption and stuff..
	
		
					$fileTypeCode = $imBlock->valueForKey('fileTypeCode');
				}
				

					$addImageAction = $this->keyForField('addImage') . "_$nid";
					
					$addImageActionArgument = $addImageAction . "_1";
					$addImageActionFileArgument = $addImageAction . "_2";
					$addImageActionFileIdentifierArgument = $addImageAction . "_3";
					$addImageActionFileSizeArgument = $addImageAction . "_4";

//					$addImageActionCaption = $addImageAction . "_6";
//					$addImageActionTargetUrl = $addImageAction . "_7";

					
					$form .= <<< EOD
<!-- Add Image -->
			<br/>
<br /><img src="Mailout/images/mailout_arrow.gif" />Select New Image<br />
<input type="file" id="$addImageActionFileArgument" name="$addImageActionFileArgument" class="cmsMailoutBodyContentBlockFile" /><br/>
<!-- Choose Image Size Mock Up-->
<br /><img src="Mailout/images/mailout_arrow.gif" />Choose Image Size<br />
EOD;

			ob_start();
			$q="SELECT filetype, CONCAT(elt(((width <=> NULL) + 1),width, ''),'x',elt(((height <=> NULL) + 1),height, '')) FROM imagedescriptor WHERE elementid=11288 AND documenttypecode='imageBlock'";
			optionList(array("id"=>$addImageActionFileSizeArgument, "name"=>$addImageActionFileSizeArgument ), false, $fileTypeCode, 0,1,$q,$db);
			$form .= ob_get_clean();

			$form .= <<< EOD
<input type="hidden" id="$addImageActionArgument" name="$addImageActionArgument" value="$imageBlock" />
<input type="hidden" id="$addImageActionFileIdentifierArgument" name="$addImageActionFileIdentifierArgument" value="$addImageActionFileArgument" />

<input onClick="return imageSubmit(this);" src="Mailout/images/mailout_accept.gif" class="cmsMailoutBodyContentBlockAddButtons" type="image" id="$addImageAction" name="$addImageAction" value="Add Image" />
EOD;
				$nid++;
				$form .= <<< EOD
</td>
EOD;
			}

			//here we need to generate some id and actions for adding and removing the various image files
			$form .= <<< EOD
</tr>
	</table>
</div>
<br />
EOD;
			return $form;
		}

		function addImageAction($imageBlock,$imageId, $fileTypeCode){
			//we need to look up the file ..
			// and the arguments and map it into the
			//newly formed obejct etc.
			//echo "**" . $imageBlock."<br/>".$imageId."<br/>" . $fileTypeCode ."**<br/>";
			if (is_null($imageId)){
				return null;
			}

			if (!key_exists($imageId, $_FILES) ||  is_null($_FILES[$imageId]) || !is_array($_FILES[$imageId])
			|| !is_uploaded_file($_FILES[$imageId]['tmp_name'])
			){
//				echo "bust";
				return null;
			}
			$f = $_FILES[$imageId];
			//echo $this->id() . " add invoke " .  $imageBlock;

			$icb = $this->valueForKey($imageBlock);
			if (is_null($icb)) {
				$icb = new $this->imageBlockClass();
			}
			$ib = array_flip($this->imageBlocks);
			$icb->takeValueForKey($ib[$imageBlock], 'imageBlockPosition' );
			// we name the image block with the parents name/id.. and its position..
			$name = "body content block " . $this->id() . " " . $imageBlock . "(". $icb->id() .")";
			$icb->takeValueForKey($name, 'imageTitle');
			$icb->takeValueForKey($fileTypeCode, 'fileTypeCode');
			
			// we need to in here fangle the request and
			// then invoke any actions and take values for request on the object
			$_FILES[ $icb->keyForField('image') ] = $f;

			$icb->takeValuesFromRequest();

			//we dont know the nid however.. tricky
			//we  know our id.. and we know.. what else??
			//save it back
			$this->takeValueForKey($icb, $imageBlock);
		}

		function deleteImageAction($imageBlock) {
			echo $this->id() . " delete invoke";
			//at this point in time we dont actually want to remove the from the app/data store
			// we just want to remove it from the email.
			$icb = $this->valueForKey($imageBlock);
			if (!is_null($icb)) {
				$this->takeValueForKey(null,$imageBlock);
			}
		}

		function changeImageAction($imageBlock,$imageId){
			echo $this->id() .  " change invoke";
			$this->addInvoke($imageBlock,$imageId);
		}


		function validateLeftImage() {
			return $this->imageBlockValidation($this->valueForKey('leftImage'));
		}

		function validateRightImage() {
			return $this->imageBlockValidation($this->valueForKey('rightImage'));
		}

		function validateCentreImage() {
			return $this->imageBlockValidation($this->valueForKey('centreImage'));
		}

		function imageBlockValidation(&$imageBlock) {
			// these need to validate true if there is nothing there..
			if (is_null($imageBlock))
				return true;

			//echo "validate image block: " . $imageBlock->id() ."<br/>";
			$valid = false;
			if (!is_null($imageBlock))
				$valid =  $imageBlock->validateForSave();
			return $valid;
		}

		function save(&$authInfo, &$db) {
			//echo "cb save: " . $this->id() . "<br/>";

			$res = new CmsStatusMessage();//temporary place holder... thing..

			foreach ($this->imageBlocks as $imageBlockId => $imageBlock){

				$ib = $this->valueForKey($imageBlock);
				if (!is_null($ib)){
					$ibr = $ib->save($authInfo, $db);
					if ($ibr->hasErrors) {
						$res->hasErrors = true;
						$res->addValidationMessageForKey('imageBlockWithId_'. $ib->valueForKey('id') ,'f_CHILD_OBJEC_FAILED_TO_SAVE',CMS_STATUS_ERROR);
					}
				}
				$this->takeValueForKey($ib, $imageBlock);
			}
			$r= null;
			if (!$res->hasErrors){
				$r = parent::save($authInfo, $db);
			}

			//merge
			if (!is_null($r) && $r->hasErrors){
				$r->messages = array_merge($r->messages,$res->messages);
				$r->hasErrors = $r->hasErrors && $res->hasErrors;
				$res = $r;
			}
			return $res;
		}

		function load($id, &$authInfo, &$db){
			$res = parent::load($id, $authInfo, $db);
			if ($res) {
				foreach($this->imageBlocks as $imageBlock){
					$this->loadImageBlock($imageBlock, $authInfo, $db);
				}
			}
			return $res;
		}

		function loadImageBlock($imageBlock, &$authInfo, &$db){
			if (is_string($this->valueForKey($imageBlock)) && strlen($this->valueForKey($imageBlock)) ==  8){
				$ib = new $this->imageBlockClass();
				$ibRes = $ib->load($this->valueForKey($imageBlock),$authInfo, $db );
				if(!$ibRes->hasErrors){
					$this->takeValueForKey($ib,$imageBlock);
				} else {
					//$this->takeBinaryDataFromFiles();//do we want to nuke things that are missing??
				}
			}
		}

		function generateHTML(&$db){
			$form = parent::generateHTML($db);

			if ($this->valueForKey('title')) {
				$form.= "<h2>" .$this->valueForKey('title') ."</h2>";
			}
			
			$images = "";
			foreach($this->imageBlocks as $imageBlock){
				$imb = $this->valueForKey($imageBlock);
				if (!is_null($imb))
					$images .= $imb->generateHTML($db);
			}
			if (strlen($images)>0){
				$form.= "<span class=\"s_contentblock_images\">";
				$form.=  $images;
				$form .= "</span>";
			}
			
			$form .="<span class=\"s_contentblock\">";
			$form .= $this->valueForKey('bodyContent');
			$form .="</span>";
			return $form;
		}

		function takeValuesFromRequest(){
			parent::takeValuesFromRequest();
			foreach($this->imageBlocks as $imageBlock){
				$imb = $this->valueForKey($imageBlock);
				if (!is_null($imb)){
					$imb->takeValuesFromRequest();
					$this->takeValueForKey($imb,$imageBlock);
				}
			}
		}
//--
	}


//helper functions
		function bodyContentBlockPageOrderSort($a, $b){
			$aPageOrder = $a->valueForKey('pageOrder');
			$bPageOrder = $b->valueForKey('pageOrder');

			return ($aPageOrder == $bPageOrder) ? 0 : ( ($aPageOrder> $bPageOrder) ? 1 : -1 );

		}





?>